const router = require('koa-router')()
const formidable = require('formidable')
const { postWork, postAvatar } = require('../model/images')
const { changeName } = require('../model/users')

router.prefix('/upload');

router.post('/textrue', async(ctx,next) => {
	const form = formidable({multiples:true,uploadDir:'public/temps/textrues',keepExtensions:true});

	await new Promise((resolve, reject) => {
		form.parse(ctx.req, async(err, fields, files) => {
			if (err) {
				reject(err);
				return ctx.body = {'code':500,'msg':err};
			}
			ctx.body = {code:200,data:`http://localhost:8080/temps/textrues/${files.files.newFilename}`}
			resolve();
		});
	});

	return;
})

router.post('/model', async(ctx,next) => {
	const form = formidable({multiples:true,uploadDir:'public/temps/models',keepExtensions:true});

	await new Promise((resolve, reject) => {
		form.parse(ctx.req, async(err, fields, files) => {
			if (err) {
				reject(err);
				return ctx.body = {'code':500,'msg':err};
			}
			ctx.body = {code:200,data:`http://localhost:8080/temps/models/${files.files.newFilename}`,name:files.files.originalFilename}
			resolve();
		});
	});

	return;
})

router.post('/works', async(ctx, next) => {
    const form = formidable({multiples:true,uploadDir:'public/images/works',keepExtensions:true});
  
    form.parse(ctx.req, async(err, fields, files) => {
        if(err) {
          ctx.body = {'code':500,'msg':err};
        }
            await postWork(fields.title,fields.userid,fields.content,`http://localhost:8080/images/works/${files.files.newFilename}`,fields.create_time);
    })
	ctx.body = {'code':200,'msg':'success'};
})

router.post('/uploadAvatar', async(ctx, next) => {
    const form = formidable({multiples:true,uploadDir:'public/images/avatar',keepExtensions:true});

	await new Promise((resolve, reject) => {
		form.parse(ctx.req, async(err, fields, files) => {
			if (err) {
				reject(err);
				return ctx.body = {'code':500,'msg':err};
			}
			ctx.body = await postAvatar(fields.userid,`http://localhost:8080/images/avatar/${files.files.newFilename}`);
			resolve();
		});
	});

	return;
})

router.post('/uploadUserName', async(ctx,next) => {
	const username = ctx.request.body.username;
	const userid = ctx.request.body.userid;

	ctx.body = await changeName(username,userid);
})

module.exports = router